package com.demo.service.riot.Async;

import com.demo.entity.riot.RankEntry;
import com.demo.entity.riot.Summoner;
import com.demo.exception.ApiException;
import com.demo.mapper.riot.RankMapper;
import com.demo.service.riot.SummonerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class RankDataAsyncService {
    private static final Logger logger = LoggerFactory.getLogger(MatchDataAsyncService.class);

    @Resource
    private final RankMapper rankMapper;

    private final SummonerService summonerService;

    public RankDataAsyncService(RankMapper rankMapper, SummonerService summonerService) {
        this.rankMapper = rankMapper;
        this.summonerService = summonerService;
    }

    @Async("dataExecutor")
    public void processRankDataAsync(String serverRegion, String puuid, List<RankEntry> rankEntries, String type) throws ApiException {
        long startTime = System.currentTimeMillis();
        logger.info("开始异步处理排位数据, puuid: {}, 数量: {}", puuid, rankEntries.size());

        try {
            if(type.equals("update")) {
                updateRankEntries(serverRegion, puuid, rankEntries);
            } else if(type.equals("create")) {
                createRankEntries(puuid, rankEntries);
            }

        } catch (Exception e) {
            logger.error("处理排位数据时发生错误", e);
        }

        long duration = System.currentTimeMillis() - startTime;
        logger.info("排位数据处理完成, puuid: {}, 耗时: {}ms", puuid, duration);
    }

    private void createRankEntries(String puuid, List<RankEntry> rankEntries) {
        rankMapper.insertRankEntries(puuid, rankEntries);
    }

    private void updateRankEntries(String serverRegion, String puuid, List<RankEntry> rankEntries) throws ApiException {
        Summoner summoner = summonerService.getSummonerByPuuid(serverRegion, puuid);
        for(RankEntry rankEntry: rankEntries) {
            rankMapper.updateRankEntries(serverRegion, summoner.getPuuid(), rankEntry);
        }
    }
}
